package com.cloud.drore.eboss.operation.service.impl;

import com.cloud.drore.eboos.common.base.BaseServiceImpl;
import com.cloud.drore.eboos.common.base.MyMapper;
import com.cloud.drore.eboos.common.base.PagePo;
import com.cloud.drore.eboos.common.base.ResultMessage;
import com.cloud.drore.eboos.common.entity.base.DictionaryVo;
import com.cloud.drore.eboos.common.entity.base.UserInfo;
import com.cloud.drore.eboos.common.util.*;


import com.cloud.drore.eboss.operation.entity.DistributorAccount;
import com.cloud.drore.eboss.operation.entity.DistributorRecharge;

import com.cloud.drore.eboss.operation.entity.po.DistributorRechargePo;
import com.cloud.drore.eboss.operation.entity.po.FinaceFlowMeterPo;
import com.cloud.drore.eboss.operation.entity.vo.DistributorAccountDeleteRechargeVo;
import com.cloud.drore.eboss.operation.entity.vo.DistributorForRedisInfoVo;
import com.cloud.drore.eboss.operation.mapper.DistributorMapper;
import com.cloud.drore.eboss.operation.mapper.DistributorRechargeMapper;
import com.cloud.drore.eboss.operation.mapper.MerchantMapper;
import com.cloud.drore.eboss.operation.service.IBaseDataFeign;
import com.cloud.drore.eboss.operation.service.IDistributorRechargeService;
import com.cloud.drore.eboss.operation.service.IFeignFinace;
import com.cloud.drore.eboss.util.DictionaryMapUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import static com.cloud.drore.eboos.common.constant.RedisConstant.OTA_CASH_POOL;
import static com.cloud.drore.eboos.common.constant.RedisConstant.TRAVEL_CASH_POOL;


/**
 * 浙江卓锐科技股份有限公司 版权所有 © Copyright 2018<br>
 *
 * @Description: 分销商充值业务层<br>
 * @Project: eboos <br>
 * @CreateDate: Created in 2018/1/4 12:45 <br>
 * @Author: <a href="410508961@qq.com">夏凯</a>
 */
@Service
public class DistributorRechargeServiceImpl extends BaseServiceImpl implements IDistributorRechargeService {

    @Resource
    DistributorRechargeMapper distributorRechargeMapper;
    @Autowired
    IFeignFinace iFeignFinace;
    @Resource
    DistributorMapper distributorMapper;
    @Resource
    MerchantMapper merchantMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    IBaseDataFeign iBaseDataFeign;
    @Autowired
    RedisKeysClockUtil redisKeysClockUtil;
    @Autowired
    FinaceSettlementHistoryServiceImpl finaceSettlementHistoryServiceImpl;

    @Override
    public MyMapper getMapper() {
        return distributorRechargeMapper;
    }

    private static final int OPERATION_FEGIN_SERVICE_SUCCESS_CODE = 8200;

    /**
     * @param id
     * @ClassName: DistributorRechargeServiceImpl
     * @Return: com.cloud.drore.eboss.operation.entity.DistributorRecharge
     * @Decription: 分销商充值查看
     * @CreateDate: Created in 2018/1/19 0019 下午 12:02
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public DistributorRecharge findDistributorRecharge(Long id) {
        return distributorRechargeMapper.selectByPrimaryKey(id);
    }

    /**
     * @param distributorRechargePo
     * @ClassName: DistributorRechargeServiceImpl
     * @Return: java.util.List<com.cloud.drore.eboss.operation.entity.DistributorRecharge>
     * @Decription: 根据时间查询单个分销商历史记录充值列表
     * @CreateDate: Created in 2018/1/19 0019 下午 4:27
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public ResultMessage<List<DistributorRecharge>> selectDistributorRechareListByTime(PagePo<DistributorRechargePo> distributorRechargePo) {

        PageHelper.startPage(distributorRechargePo);
        List<DistributorRecharge> distributorRechargeList = distributorRechargeMapper.selctDistributorRechareListByTime(distributorRechargePo);
        PageInfo pageInfo = new PageInfo<>(distributorRechargeList);
        return ResultMessage.success(pageInfo);
    }

    /**
     * @param id
     * @ClassName: DistributorRechargeServiceImpl
     * @Return: java.util.List<com.cloud.drore.eboss.operation.entity.DistributorRecharge>
     * @Decription: 根据分销商id，查询充值记录列表
     * @CreateDate: Created in 2018/1/19 0019 下午 4:17
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public List<DistributorRecharge> selctDistributorRechareList(Long id) {
        return distributorRechargeMapper.selctDistributorRechareList(id);
    }


    public ResultMessage findByName(PagePo page) {
        PageHelper.startPage(page);
        List list = distributorRechargeMapper.selectAll();
        return new ResultMessage(new PageInfo<>(list));
    }

    /**
     * @param distributorRecharge
     * @ClassName: FinaceSupplierRechargeServiceImpl
     * @Return: void
     * @Decription: 分销商充值金额的时候更新分销商账户列表
     * @CreateDate: Created in 2018/2/8 0008 下午 8:29
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    //@Klock(name = "xiakai",lockType=Fair,leaseTime=60)
    @Transactional
    public void addDistributorAccountAmount(DistributorRecharge distributorRecharge) {
        //查询得到分销商账户余额信息
        DistributorAccount distributorAccount = distributorMapper.selectDistributorId(distributorRecharge.getDistributorId());
        BigDecimal distributorAccountAmount = distributorAccount.getAccountBalance();
        //账户余额信息
        BigDecimal distributorAccountAmountTotal;
        //已结算金额更新
        if (null == distributorAccountAmount || "".equals(distributorAccountAmount)) {
            distributorAccountAmountTotal = new BigDecimal("0").add(distributorAccountAmount);
        } else {
            distributorAccountAmountTotal = distributorRecharge.getAccountArrivalAmount().add(distributorAccountAmount);
        }
        UserInfo currentUser = LocalData.getCurrentUser();
        distributorRecharge.setOperationPerson(currentUser.getUsername());
        distributorRecharge.setAccountBalance(distributorAccountAmountTotal);
        distributorRecharge.setRechargeMethod("线下充值");
        //插入充值记录
        Object insertFlag = insert(distributorRecharge);
        distributorRecharge = (DistributorRecharge) insertFlag;
        if (null == insertFlag || "".equals(insertFlag)) {
            throw new RuntimeException("上传的字段数据类型有误!");
        }
        //修改分销商账户最新一次的充值时间，另外再修改账户余额信息
        Date date = LocalDateAndDateTransformUtil.localDateTimeToDate(LocalDateTime.now());
        //添加分销商账户充值流水
        List<FinaceFlowMeterPo> finaceFlowMeterPos = new ArrayList<>();
        finaceFlowMeterPos.add(produceRechargeFlow(distributorRecharge));
        ResultMessage resultMessage = iFeignFinace.produceAccountRechargeFlowMeter(finaceFlowMeterPos);
        if (resultMessage.getCode() != OPERATION_FEGIN_SERVICE_SUCCESS_CODE) {
            throw new RuntimeException("远程调用插入流水失败！");
        }
        //通过分销商id查询分销商账户信息
        distributorRechargeMapper.updateDistributorRechargeTimeAndAmount(distributorAccount.getId(), distributorAccountAmountTotal, DateToStringUtil.getStringDateTime(date));

        //更新redis金额信息
        String key;
        //判断旅行社还是ota
        String distributorIndustry = merchantMapper.queryMerchantIndustry(distributorRecharge.getDistributorId());
        //判断性质
        if (null == distributorIndustry || "".equals(distributorIndustry)) {
            throw new RuntimeException("分销商属性设置异常！");
        }
        if (distributorIndustry.equals("MERCHANT_INDUSTRY_OTA")) {
            key = distributorAccount.getMerchantNum() + OTA_CASH_POOL;
        } else if (distributorIndustry.equals("MERCHANT_INDUSTRY_HOUSEKEEPER")) {
            key = distributorAccount.getMerchantNum() + TRAVEL_CASH_POOL;
        } else {
            throw new RuntimeException("redis的key值获取失败！");
        }
        redisKeysClockUtil.cashPoolChange(key, distributorRecharge.getAccountArrivalAmount(), true);
    }


    /**
     * @param distributorRecharge
     * @ClassName: DistributorRechargeServiceImpl
     * @Return: com.cloud.drore.eboss.operation.entity.po.FinaceFlowMeterPo
     * @Decription: 得到分销商充值生成的流水对象
     * @CreateDate: Created in 2018/3/19 0019 下午 8:47
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public FinaceFlowMeterPo produceRechargeFlow(DistributorRecharge distributorRecharge) {
        Date date = LocalDateAndDateTransformUtil.localDateTimeToDate(LocalDateTime.now());
        FinaceFlowMeterPo finaceFlowMeterPo = new FinaceFlowMeterPo();
        finaceFlowMeterPo.setDistributorId(distributorRecharge.getDistributorId());  //分销商id
        finaceFlowMeterPo.setRechargeRecordId(distributorRecharge.getId());//分销商充值表id
        finaceFlowMeterPo.setEventAmount(distributorRecharge.getAccountArrivalAmount());//交易金额
        finaceFlowMeterPo.setEventType(0);//事件类型：0账户 1订单
        finaceFlowMeterPo.setFlowNum(CodingGeneration.getFlowGenerationCodingNum("ACCOUNT_EVENT_RECHARGE")); //流水号
        finaceFlowMeterPo.setOrderEventStatus("ACCOUNT_EVENT_RECHARGE");//事件状态
        finaceFlowMeterPo.setOrderProduceTime(date);//时间
        finaceFlowMeterPo.setCreatedBy(LocalData.getCurrentUser().getTypeId().toString());
        finaceFlowMeterPo.setCreatedDate(date);
        return finaceFlowMeterPo;

    }

    /**
     * @param id
     * @ClassName: DistributorAccountServiceImpl
     * @Return: int
     * @Decription: 超级管理员通过表id删除分销商历史充值记录信息，这里要判断是否是管理员权限
     * @CreateDate: Created in 2018/2/24 0024 下午 1:28
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    @Transactional
    public int deleteDistributorRechargeHistoryById(Long id) {
        //查询得到分销商账户余额信息需要重新进行更新的账户余额信息
        DistributorAccountDeleteRechargeVo distributorAccountAmount = distributorMapper.selectWhenDeleteDistributorAccountAmount(id);
        //修改分销商账户余额信息
        distributorMapper.updateDistributorAccoutAmount(distributorAccountAmount.getDistributorId(), distributorAccountAmount.getDistributorAccountAmount());

        //添加分销商账户作废流水
        FinaceFlowMeterPo finaceFlowMeterPo = new FinaceFlowMeterPo();
        finaceFlowMeterPo.setDistributorId(distributorAccountAmount.getDistributorId());  //分销商id
        finaceFlowMeterPo.setEventAmount(distributorAccountAmount.getEventRelationAmount());//交易金额
        finaceFlowMeterPo.setEventType(0);//事件类型：0账户 1订单
        finaceFlowMeterPo.setFlowNum(CodingGeneration.getFlowGenerationCodingNum("ACCOUNT_EVENT_DELETE")); //流水号
        finaceFlowMeterPo.setOrderEventStatus("ACCOUNT_EVENT_DELETE");//事件状态
        Date date = LocalDateAndDateTransformUtil.localDateTimeToDate(LocalDateTime.now());
        finaceFlowMeterPo.setOrderProduceTime(date);//时间
        finaceFlowMeterPo.setCreatedDate(date);
        finaceFlowMeterPo.setCreatedBy(LocalData.getCurrentUser().getTypeId().toString());
        List<FinaceFlowMeterPo> finaceFlowMeterPos = new ArrayList<>();
        finaceFlowMeterPos.add(finaceFlowMeterPo);

        //查询当前凭证是否已经是删除状态
        int deleteFlag = distributorRechargeMapper.queryRechargeRecordState(id);
        if (deleteFlag == 1) {
            throw new RuntimeException("该凭证信息已经删除了！");
        }
        //逻辑删除分销商账户的充值信息
        int flag = distributorRechargeMapper.updateDistributorRechargeHistory(id);

        ResultMessage resultMessage = iFeignFinace.produceAccountRechargeFlowMeter(finaceFlowMeterPos);
        if (resultMessage.getCode() != OPERATION_FEGIN_SERVICE_SUCCESS_CODE) {
            throw new RuntimeException("远程调用插入流水失败！");
        }

        //更新redis上面的数据信息
        DistributorForRedisInfoVo distributorForRedisInfoVo = new DistributorForRedisInfoVo();
        distributorForRedisInfoVo.setAccountBalance(distributorAccountAmount.getEventRelationAmount());
        distributorForRedisInfoVo.setMerchantIndustry(distributorAccountAmount.getDistributorIndustry());
        distributorForRedisInfoVo.setMerchantNum(distributorAccountAmount.getMerchantNum());
        String key = finaceSettlementHistoryServiceImpl.judgeOtaOrHousekeeper(distributorForRedisInfoVo);
        redisKeysClockUtil.cashPoolChange(key, distributorAccountAmount.getEventRelationAmount(), false);

        return flag;
    }

    /**
     * @param
     * @ClassName: DistributorRechargeServiceImpl
     * @Return: java.util.List<com.cloud.drore.eboos.common.entity.base.DictionaryVo>
     * @Decription: 流水统计查看下拉框初始化
     * @CreateDate: Created in 2018/3/26 0026 下午 8:17
     * @Author: <a href="410508961@qq.com">夏凯</a>
     * @Modify:
     */
    public List<DictionaryVo> initOperationStatusList() {
        List<DictionaryVo> order_event_status = iBaseDataFeign.getDicListMapByCodeVo("ORDER_EVENT_STATUS");
        List<DictionaryVo> account_event_status = iBaseDataFeign.getDicListMapByCodeVo("ACCOUNT_EVENT_STATUS");
        order_event_status.addAll(account_event_status);
        return order_event_status;
    }

}
